package com.hpc.Service;

import entity.systemConstant;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;

@Service
public class MyScheduledService {
    @Resource
    private com.hpc.mapper.articleMapper articleMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private articleService articleService;
    @Resource
    private com.hpc.mapper.saveMapper1 saveMapper1;
    @Scheduled(cron = "*/5 * * * * *")//每5秒执行一次将redis中的文章的喜欢数持久化进mysql数据库
    public void hotsave(){
//        System.out.println("我执行了");
        Map<String,Integer> entries = redisTemplate.opsForHash().entries(systemConstant.LIKESOFARTICLE);
        entries.forEach((k,v)->{
            articleMapper.hotsave(k,v);
        });
    }
    @Scheduled(cron = "0 0 0 ? * MON")
    public void hotTop5(){
        articleService.hotweekendly();
    }
    @Scheduled(cron = "*/5 * * * * *")//每5秒执行一次将redis中的文章的喜欢数持久化进mysql数据库表likeOfUser
    public void likesOfArticleSave(){
        try {
            Boolean aBoolean = redisTemplate.hasKey(systemConstant.LIKESOFARTICLE);
            if (aBoolean){
                saveMapper1.likesOfArticleTruncate();
                Map<String,Integer> entries = redisTemplate.opsForHash().entries(systemConstant.LIKESOFARTICLE);
                entries.forEach((k,v)->{
                    saveMapper1.likesOfdArticle(UUID.randomUUID().toString(),k,v);
//                    System.out.println("持久化成功！-likesOfArticleSave！");
                });
            }
        }catch (Exception e){
            System.out.println("持久化失败-likesOfArticleSave！");
        }
    }
}
